package com.umakr.ax.security.core;

import com.umakr.ax.security.core.ano.AccessType;
import com.umakr.ax.security.mapper.ResMapper;
import com.umakr.ax.security.mapper.RoleMapper;
import com.umakr.ax.security.model.Res;
import com.umakr.ax.security.model.Role;
import com.umakr.ax.security.model.SecurityUser;
import com.umakr.ax.security.service.ResService;
import com.umakr.ax.security.service.SecurityUserDetailsServiceImpl;
import com.umakr.ax.utils.WebUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *
 * @author Administrator
 * @date 2015/9/14
 */
public class ResourceRoleMappingSecurityMetaSource implements FilterInvocationSecurityMetadataSource{

    @Autowired
    SecurityUserDetailsServiceImpl securityUserDetailsServiceImpl;

    private static final String PATTERN_START = "/";

    private final Map<RequestMatcher, Collection<ConfigAttribute>> resourcesRoleMaping = new LinkedHashMap<>();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) {
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
        Collection<ConfigAttribute> configAttributes = Lists.newArrayList();
        //TODO 这里还要做缓存。以提升性能。
        /**
         * resourcesRoleMaping
         */
        resourcesRoleMaping.forEach((RequestMatcher rm,Collection<ConfigAttribute> cg) ->{
            if (rm.matches(request)) {
                configAttributes.addAll(cg);
            }
        });
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        Set<ConfigAttribute> allAttributes = new HashSet<>();

        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : resourcesRoleMaping
                .entrySet()) {
            allAttributes.addAll(entry.getValue());
        }
        return allAttributes;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    public void structure(){

        resourcesRoleMaping.clear();

        Collection<ConfigAttribute> configAttributes = Lists.newArrayList();
        configAttributes.add(new SecurityConfig("ROLE_ADMIN"));
        //如果是超级管理员，拥有所有权限
        resourcesRoleMaping.put(new AntPathRequestMatcher("/**",null,true),configAttributes);


        ResMapper resMapper = WebUtil.getBean(ResMapper.class);
        List<Res> sResList = resMapper.selectList(null);

        for(Res sRes : sResList){
            List<Role> codes = WebUtil.getBean(RoleMapper.class).queryRoleByResId(sRes.getId());
            Collection<ConfigAttribute> configAttributesTemp = Lists.newArrayList();
            codes.forEach((Role s)->
                    configAttributesTemp.add(new SecurityConfig(s.getRoleCode()))
            );
            resourcesRoleMaping.put(new AntPathRequestMatcher(sRes.getResUrl(),null,true),configAttributesTemp);
        }

        List<String> accessByUser = WebUtil.getBean(ResService.class).method(AccessType.ACCESS_BY_ROLE_USER);
        if(accessByUser.isEmpty()){
            Collection<ConfigAttribute> configAttributesTemp = Lists.newArrayList();
            configAttributesTemp.add(new SecurityConfig("ROLE_USER"));
            for(String p : accessByUser){
                resourcesRoleMaping.put(new AntPathRequestMatcher(p,null,true),configAttributesTemp);
            }
        }
    }

    public Map<String,Boolean> matchUrl(String url){
        SecurityUser sUser = (SecurityUser) securityUserDetailsServiceImpl.currentUser();
        final String[] userAuth = {""};
        sUser.getAuthorities().forEach((GrantedAuthority gf)->
            userAuth[0] = gf.getAuthority()+";"+ userAuth[0]
        );
        Map<String,Boolean> map = Maps.newHashMap();
        resourcesRoleMaping.forEach((RequestMatcher rm,Collection<ConfigAttribute> cg)->{
            AntPathRequestMatcher antPathRequestMatcher = (AntPathRequestMatcher)rm;
            String pattern = antPathRequestMatcher.getPattern();
            if(pattern.startsWith(PATTERN_START+url)){
                cg.forEach((ConfigAttribute configAttribute)-> {
                    if(userAuth[0].contains(configAttribute.getAttribute())){
                        map.put(pattern.replaceAll("/","_"),true);
                    }
                });
            }
        });
        map.put("isAdmin",userAuth[0].contains("ROLE_ADMIN"));
        return map;
    }
}
